package com.dehui.traders.ui.optioanl;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.dehui.traders.BR;
import com.dehui.traders.R;
import com.dehui.traders.ui.optioanl.adapter.OptionalStockManagerAdapter;
import com.dehui.traders.bean.BaseResponse;
import com.dehui.traders.bean.OptionalCode;
import com.dehui.traders.bean.OptionalCodeRank;
import com.dehui.traders.config.Preferences;
import com.dehui.traders.databinding.FragmentOptionalStockManagerBinding;
import com.dehui.traders.service.CallListener;
import com.dehui.traders.service.NetImpl;
import com.dehui.traders.ui.base.AppFragment;
import com.dehui.traders.utils.SimpleDividerDecoration;
import com.dehui.traders.utils.UserHelp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yanzhenjie.recyclerview.swipe.touch.OnItemMoveListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import me.goldze.mvvmhabit.utils.ToastUtils;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by hqq on 18.4.19.
 */

public class OptionalStockManagerFragment extends AppFragment<FragmentOptionalStockManagerBinding,OptionalStockManagerViewModel> implements OnItemMoveListener, OptionalStockManagerAdapter.OnItemClick {

    private List<OptionalCode > stockList = new ArrayList<>();
    private OptionalStockManagerAdapter adapter;
    private int selectNum = 0;

    @Override
    public int initContentView() {
        return R.layout.fragment_optional_stock_manager;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public OptionalStockManagerViewModel initViewModel() {
        return new OptionalStockManagerViewModel(getContext(),this);
    }

    @Override
    public void initData() {

        String myOpitonCode = Preferences.getMyOpitonCode();
        try {
            List<OptionalCodeRank> codeList =new Gson().fromJson(myOpitonCode, new TypeToken<List<OptionalCodeRank>>() {}.getType());
            stockList.clear();
            for (OptionalCodeRank item : codeList){
                stockList.add(new OptionalCode(item.code,item.status,item.name,item.market));
            }
        }catch (Exception e){

        }

        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerView.setLongPressDragEnabled(true);
        binding.recyclerView.setOnItemMoveListener(this);

        adapter = new OptionalStockManagerAdapter(stockList, R.layout.list_item_optional_stock_manager,binding.recyclerView);
        adapter.setOnItemClick(this);
        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.addItemDecoration(new SimpleDividerDecoration(getContext()));
    }


    @Override
    public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
        if (srcHolder.getItemViewType() != targetHolder.getItemViewType()) return false;
        int fromPosition = srcHolder.getAdapterPosition();
        int toPosition = targetHolder.getAdapterPosition();

        Collections.swap(stockList, fromPosition, toPosition);
        adapter.notifyItemMoved(fromPosition, toPosition);
        return true;
    }

    @Override
    public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {

    }


    @Override
    public void onStick(int pos, List<OptionalCode> list) {
        OptionalCode optionalCode = list.get(pos);
        list.remove(pos);
        list.add(0,optionalCode);
        stockList.clear();
        stockList.addAll(list);
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onRemind(int pos) {
        OptionalCode optionalCode = stockList.get(pos);
        int status = optionalCode.getStatus();
        String newStatus;
        if (status == 0){
            stockList.get(pos).setStatus(1);
            newStatus = "1";
        }else{
            stockList.get(pos).setStatus(0);
            newStatus = "0";
        }

        Call<BaseResponse<String>> call = NetImpl.saveCode(optionalCode.getCode(), optionalCode.getMarket(), UserHelp.getUserId(), newStatus, optionalCode.getName(), "0");
        call.enqueue(new CallListener<BaseResponse<String>>() {
            @Override
            public void _onResponse(Response<BaseResponse<String>> response) {
                BaseResponse<String> baseResponse = response.body();
                if (baseResponse.status == 200){
                    if (status == 0)
                        ToastUtils.showShort("已成功订阅");
                    else
                        ToastUtils.showShort("已取消订阅");

                    adapter.notifyDataSetChanged();
                    List<OptionalCodeRank> codeRanks = new ArrayList<>();
                    for (int i = 0; i < stockList.size(); i++){
                        OptionalCode oc = stockList.get(i);
                        String code = oc.getCode();
                        OptionalCodeRank codeRank = new OptionalCodeRank(oc.getName(),code,oc.getMarket(),oc.getStatus());
                        codeRanks.add(codeRank);
                    }
                    String codestr = new Gson().toJson(codeRanks);
                    Preferences.saveMyOpitonCode(codestr);

                }else{
                    ToastUtils.showShort(R.string.add_failed);
                }
            }

            @Override
            public void _onFailure() {
                ToastUtils.showShort(R.string.add_failed);
            }
        });

    }

    @Override
    public void onSelect() {
        selectNum = 0;
        for (OptionalCode item : stockList){
            if (item.isSelect()){
                selectNum ++;
            }
        }
        binding.tvDelete.setText("删除(" + selectNum + ")");
        binding.ivSelectAll.setSelected(selectNum == stockList.size());
    }

    public List<OptionalCode> getStockList() {
        return stockList;
    }


    public void selectAll() {
        binding.ivSelectAll.setSelected(!binding.ivSelectAll.isSelected());
        boolean selected = binding.ivSelectAll.isSelected();
        for (OptionalCode item : stockList){
            item.setSelect(selected);
        }
        if (selected){
            binding.tvDelete.setText("删除(" + stockList.size() + ")");
        }else{
            binding.tvDelete.setText("删除(0)");

        }
        adapter.notifyDataSetChanged();
    }


    public void notifyDelete() {
        List<OptionalCode> list = new ArrayList<>();
        for (int i = 0; i < stockList.size(); i++){
            OptionalCode optionalCode = stockList.get(i);
            if (!optionalCode.isSelect()){
                list.add(optionalCode);
            }
        }
        stockList.clear();
        stockList.addAll(list);
        adapter.refresh(stockList);
        binding.tvDelete.setText("删除(0)");
    }


}
